namespace MyMessenger.Web
{
	using System.Web;
	using Castle.Windsor;
	using Castle.Windsor.Configuration.Interpreters;
    using Castle.ActiveRecord;
    using Castle.ActiveRecord.Framework;
    using NHibernate.Cfg;
    using NHibernate;
    using NHibernate.Tool.hbm2ddl;
    using MyMessenger.Core;

	public class GlobalApplication : HttpApplication, IContainerAccessor
	{
		private static IWindsorContainer container;
        private static SessionScope scope;

		public GlobalApplication()
		{
 		}

		#region IContainerAccessor

		public IWindsorContainer Container
		{
			get { return container; }
		}

		#endregion


		public void Application_OnStart()
		{
			container = new WindsorContainer(new XmlInterpreter());
            scope = new SessionScope();
            CreatreSchema();
        }

		public void Application_OnEnd() 
		{
			container.Dispose();
            scope.Dispose();
		}

        private void CreatreSchema()
        {
            ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
            Configuration configuration = sessionFactoryHolder.GetConfiguration(typeof(ActiveRecordBase));
            ISession session = sessionFactoryHolder.CreateSession(typeof(ActiveRecordBase));
            new SchemaExport(configuration).Execute(false, true, false, true, session.Connection, null);

            AddUser("admin", "123");
            AddUser("adam", "adam");
            AddUser("marcel", "marcel");
            AddUser("nemo", "nemo");
            AddUser("mariusz", "mariusz");
            AddUser("user1", "user1");
            AddUser("user2", "user2");
            AddUser("user3", "user3");

            scope.Flush();          
        }

        private void AddUser(string name, string passsword)
        {
            User user = new User();
            user.Name = name;
            user.Password = passsword;
            ActiveRecordMediator<User>.Save(user);
        }
	}
}
